package com.example.easydownloadback.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.example.easydownloadback.domin.UserDTO;
import com.example.easydownloadback.util.RedisPrefix;
import com.example.easydownloadback.util.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 刷新token时间拦截器
 * 1.请求头获取token，并通过token从redis获取登录对象，然后放入ThreadLocal，让后续LoginInterceptor拦截器来判断登录状态
 * 2.如果能从redis获取到登录对象，则刷新其ttl
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 如果为空直接放行
            return true;
        }
        // 2.通过token获取redis中的用户
        String tokenKey = RedisPrefix.LOGIN_USER_KEY + token;
        // 这里为空会返回一个空的map
        Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(tokenKey);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            // 如果为空直接放行
            return true;
        }
        // 5.将查询到的Hash数据，转换为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 6.存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        // 7.刷新token有效期
        stringRedisTemplate.expire(tokenKey, RedisPrefix.LOGIN_USER_TTL, TimeUnit.MINUTES);
        // 8.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserHolder.removeUser();
    }
}
